<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result  v-if="isResultShow" :search-text="searchText"/>
    <!-- 联想建议 -->
    <search-suggestion v-else-if="searchText" :search-text="searchText"
    @search="onSearch"/>
    <!-- 搜索历史记录 -->
    <search-history v-else :searchHistory="searchHistory"
    @clear-search-histories="searchHistory = []" @search ="onSearch" />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  data () {
    return {
      searchText: '',
      isResultShow: false, // 控制搜搜结果的展示
      searchHistory: getItem('TOUTIAO_SEARCH_HIETORIES') || [] // 搜索历史记录
    }
  },
  watch: {
    searchHistory (value) {
      // 同步到本地存储
      setItem('TOUTIAO_SEARCH_HIETORIES', value)
    }
  },
  methods: {
    onSearch  (val) {
      // 更新文本框内容
      this.searchText = val
      // 存储搜索历史记录
      // 不能有重复历史记录、最新的排在最前面
      const index = this.searchHistory.indexOf(val)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      this.searchHistory.unshift(val)
      // 渲染搜索结果
      this.isResult = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 106px;
  .van-search__action {
    color: #fff;
  }
  .van-search {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1;
    }
}
</style>
